<template>
  <view class="address-edit-page">
    <!-- 顶部导航栏 -->
    <view class="custom-nav-bar">
      <view class="nav-left" @click="navBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-title">{{ isEditing ? '编辑地址' : '新增地址' }}</view>
      <view class="nav-right" @click="saveAddress">
        <text class="save-btn">保存</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-container">
      <view class="form-group">
        <view class="form-label required">收货人</view>
        <view class="form-control">
          <input 
		    style="height: 100rpx;line-height: 100rpx;"
            v-model="addressForm.name" 
            placeholder="请输入收货人姓名"
            maxlength="20"
            @input="validateForm"
          />
        </view>
      </view>
      
      <view class="form-group">
        <view class="form-label required">手机号码</view>
        <view class="form-control">
          <input 
		    style="height: 100rpx;line-height: 100rpx;"
            v-model="addressForm.phone" 
            placeholder="请输入手机号码"
            type="number"
            maxlength="11"
            @input="validateForm"
          />
        </view>
      </view>
      
      <view class="form-group">
        <view class="form-label required">所在地区</view>
        <view class="form-control">
          <picker 
            mode="region" 
            :value="[addressForm.province, addressForm.city, addressForm.district]"
            @change="onRegionChange"
            custom-item="全部"
          >
            <view class="picker-view">
              <text v-if="addressForm.province && addressForm.city && addressForm.district">
                {{ addressForm.province }} {{ addressForm.city }} {{ addressForm.district }}
              </text>
              <text v-else class="placeholder">请选择所在地区</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
      
      <view class="form-group">
        <view class="form-label required">详细地址</view>
        <view class="form-control">
          <textarea 
            v-model="addressForm.street" 
            placeholder="请输入详细地址，如街道、门牌号等"
            maxlength="200"
            rows="4"
            @input="validateForm"
          ></textarea>
          <view class="word-count">{{ addressForm.street.length }}/200</view>
        </view>
      </view>
      
      <view class="form-group">
        <view class="form-label">标签</view>
        <view class="form-control tags-container">
          <view 
            class="address-tag" 
            :class="{ selected: addressForm.tag === tag.value }"
            @click="selectTag(tag.value)"
            v-for="tag in tagOptions"
            :key="tag.value"
          >
            {{ tag.name }}
          </view>
          <view class="address-tag custom-tag" @click="showCustomTagInput">
            + 自定义
          </view>
        </view>
      </view>
      
      <view class="default-address-option">
        <view class="option-label">设为默认地址</view>
        <view class="option-toggle">
          <switch 
            v-model="addressForm.isDefault" 
            color="#165DFF"
          ></switch>
        </view>
      </view>
    </view>

    <!-- 自定义标签输入弹窗 -->
    <u-popup 
      :show="tagPopup" 
      mode="center"
      @close="tagPopup=false"
    >
      <view class="tag-dialog">
        <view class="dialog-title">添加自定义标签</view>
        <view class="dialog-input">
          <input 
		   style="height: 100rpx;line-height: 100rpx;"
            v-model="customTagText" 
            placeholder="请输入标签名称（最多5个字）"
            maxlength="5"
          />
        </view>
        <view class="dialog-actions">
          <button class="cancel-btn" @click="closeTagPopup">取消</button>
          <button class="confirm-btn" @click="confirmCustomTag">确认</button>
        </view>
      </view>
    </u-popup>


  </view>
</template>

<script>


export default {

  data() {
    return {
	  tagPopup:false,
      // 是否为编辑模式
      isEditing: false,
      // 当前编辑的地址ID
      addressId: null,
      // 地址表单数据
      addressForm: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        street: '',
        tag: '',
        isDefault: false
      },
      // 地址标签选项
      tagOptions: [
        { name: '家', value: 'home' },
        { name: '公司', value: 'company' },
        { name: '学校', value: 'school' },
        { name: '常用', value: 'frequent' }
      ],
      // 自定义标签输入
      customTagText: '',
      // 表单是否有效
      formValid: false
    };
  },
  
  onLoad(options) {
    // 如果有地址ID参数，则为编辑模式
    if (options.id) {
      this.isEditing = true;
      this.addressId = options.id;
      this.loadAddressData();
    } else {
      // 新增地址时，如果没有默认地址，则默认设为默认
      const addresses = uni.getStorageSync('userAddresses') || [];
      if (addresses.length === 0) {
        this.addressForm.isDefault = true;
      }
    }
  },
  
  methods: {
    // 返回上一页
    navBack() {
      uni.navigateBack({ delta: 1 });
    },
    
    // 加载地址数据
    loadAddressData() {
      const addresses = uni.getStorageSync('userAddresses') || [];
      const address = addresses.find(item => item.id === this.addressId);
      
      if (address) {
        this.addressForm = { ...address };
      } else {
        // 如果地址不存在，返回上一页
        this.navBack();
      }
    },
    
    // 地区选择变化
    onRegionChange(e) {
      const region = e.detail.value;
      this.addressForm.province = region[0];
      this.addressForm.city = region[1];
      this.addressForm.district = region[2];
      this.validateForm();
    },
    
    // 选择标签
    selectTag(tagValue) {
      this.addressForm.tag = tagValue;
    },
    
    // 显示自定义标签输入框
    showCustomTagInput() {
      this.customTagText = '';
      this.tagPopup = true;
    },
    
    // 关闭自定义标签弹窗
    closeTagPopup() {
      this.tagPopup = false
    },
    
    // 确认自定义标签
    confirmCustomTag() {
      if (this.customTagText.trim()) {
        // 添加到标签选项并选中
        const newTag = {
          name: this.customTagText.trim(),
          value: 'custom_' + Date.now()
        };
        this.tagOptions.push(newTag);
        this.addressForm.tag = newTag.value;
        this.tagPopup = false;
      } else {
       uni.showToast({
       	icon:'none',
		title:'请输入标签名称'
       })
      }
    },
    
    // 验证表单
    validateForm() {
      const phoneReg = /^1[3-9]\d{9}$/;
      
      this.formValid = !!this.addressForm.name &&
                     phoneReg.test(this.addressForm.phone) &&
                     !!this.addressForm.province &&
                     !!this.addressForm.city &&
                     !!this.addressForm.district &&
                     !!this.addressForm.street;
    },
    
    // 保存地址
    saveAddress() {
      if (!this.formValid) {
       
		uni.showToast({
			icon:'none',
			title:'请完善地址信息'
		})
        return;
      }
      
      const addresses = uni.getStorageSync('userAddresses') || [];
      
      if (this.isEditing) {
        // 编辑现有地址
        const index = addresses.findIndex(item => item.id === this.addressId);
        if (index !== -1) {
          addresses[index] = { ...this.addressForm };
        }
      } else {
        // 添加新地址
        // 如果设为默认，需要将其他地址的默认状态取消
        if (this.addressForm.isDefault) {
          addresses.forEach(item => {
            item.isDefault = false;
          });
        }
        
        addresses.push({
          ...this.addressForm,
          id: 'addr_' + Date.now() // 生成唯一ID
        });
      }
      
      // 保存到本地存储
      uni.setStorageSync('userAddresses', addresses);
      
      // 提示并返回上一页
    uni.showToast({
    	icon:'none',
		title:this.isEditing ? '地址已更新' : '地址已添加'
    })
      
      setTimeout(() => {
        this.navBack();
      }, 1500);
    }
  }
};
</script>

<style scoped lang="scss">
// 颜色变量
$primary-color: #165DFF;
$primary-light: #E8F3FF;
$text-primary: #1D2129;
$text-secondary: #4E5969;
$text-tertiary: #86909C;
$background: #F5F7FA;
$card-bg: #FFFFFF;
$border-color: #E5E6EB;
$danger-color: #F5222D;

.address-edit-page {
  background-color: $background;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  padding-top: var(--status-bar-height);
}

// 自定义导航栏
.custom-nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
  padding: 0 30rpx;
  background-color: $card-bg;
  border-bottom: 1px solid $border-color;
  
  .nav-left, .nav-right {
    width: 80rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .back-icon {
    font-size: 45rpx;
    color: $text-primary;
  }
  
  .save-btn {
    font-size: 30rpx;
    color: $primary-color;
    font-weight: 500;
  }
  
  .nav-title {
    font-size: 34rpx;
    font-weight: 600;
    color: $text-primary;
  }
}

// 表单容器
.form-container {
  padding: 25rpx 30rpx;
  
  .form-group {
    margin-bottom: 30rpx;
    
    .form-label {
      display: block;
      font-size: 28rpx;
      color: $text-primary;
      margin-bottom: 15rpx;
      font-weight: 500;
      
      &.required::after {
        content: '*';
        color: $danger-color;
        margin-left: 8rpx;
      }
    }
    
    .form-control {
      position: relative;
      
      input, textarea {
        width: 100%;
        padding: 22rpx;
        background-color: $card-bg;
        border: 1px solid $border-color;
        border-radius: 12rpx;
        font-size: 26rpx;
        color: $text-primary;
        box-sizing: border-box;
      }
      
      textarea {
        min-height: 160rpx;
        resize: none;
        padding-top: 20rpx;
      }
      
      input::placeholder, textarea::placeholder {
        color: $text-tertiary;
      }
      
      .word-count {
        position: absolute;
        right: 20rpx;
        bottom: 15rpx;
        font-size: 22rpx;
        color: $text-tertiary;
      }
    }
  }
  
  // 选择器样式
  .picker-view {
    width: 95%;
    padding: 15rpx;
    background-color: $card-bg;
    border: 1px solid $border-color;
    border-radius: 12rpx;
    font-size: 26rpx;
    color: $text-primary;
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 76rpx;
    
    .placeholder {
      color: $text-tertiary;
    }
    
    .picker-arrow {
      color: $text-tertiary;
      font-size: 26rpx;
    }
  }
  
  // 标签容器
  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 15rpx;
    padding: 10rpx 0;
    
    .address-tag {
      padding: 12rpx 25rpx;
      background-color: $background;
      border: 1px solid $border-color;
      border-radius: 25rpx;
      font-size: 24rpx;
      color: $text-secondary;
      white-space: nowrap;
      
      &.selected {
        background-color: $primary-light;
        border-color: $primary-color;
        color: $primary-color;
      }
      
      &.custom-tag {
        color: $primary-color;
        border: 1px dashed $primary-color;
      }
    }
  }
  
  // 默认地址选项
  .default-address-option {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20rpx;
    padding: 0 10rpx;
    
    .option-label {
      font-size: 28rpx;
      color: $text-primary;
    }
    
    .option-toggle {
      transform: scale(1.2);
    }
  }
}

// 自定义标签弹窗
.tag-dialog {
  width: 540rpx;
  background-color: $card-bg;
  border-radius: 20rpx;
  padding: 35rpx;
  
  .dialog-title {
    font-size: 30rpx;
    font-weight: 600;
    color: $text-primary;
    text-align: center;
    margin-bottom: 30rpx;
  }
  
  .dialog-input {
    margin-bottom: 35rpx;
    
    input {
      width: 100%;
      padding: 22rpx;
      background-color: $background;
      border: 1px solid $border-color;
      border-radius: 12rpx;
      font-size: 26rpx;
      color: $text-primary;
      box-sizing: border-box;
    }
  }
  
  .dialog-actions {
    display: flex;
    gap: 20rpx;
    
    .cancel-btn, .confirm-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
    }
    
    .cancel-btn {
      background-color: $background;
      color: $text-primary;
      border: 1px solid $border-color;
    }
    
    .confirm-btn {
      background-color: $primary-color;
      color: #fff;
      border: none;
    }
  }
}
</style>
    